﻿using e_commerce.BLL.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using e_commerce.BLL.Models;

namespace e_commerce.BLL.Services
{
    public class GoodsManager:IDisposable
    {
        private commerceDbContext _dbContext;
        public GoodsManager()
        {
            _dbContext = new commerceDbContext();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }

        public IEnumerable<GoodsInfo> GetGoodsByCategory(int category)
        {
            return category == 0 ? _dbContext.GoodsInfo :
                _dbContext.GoodsInfo.Where(g => g.Category == category&&!g.IsDelete);
        }
        public void SaveChanges()
        {
            _dbContext.SaveChanges();
        }

        public GoodsInfo GetGoodsById(int goodsId)
        {
            var goods = _dbContext.GoodsInfo.SingleOrDefault(g => g.GoodsId == goodsId);
            if(goods == null)
            {
                throw new Exception("未查询到该商品");
            }
            else if (goods.IsDelete)
            {
                throw new Exception("商品已被删除");
            }
            return goods;
        }

        public IEnumerable<GoodsInfo> GetGoodsByCount(int count,int category)
        {
            var goods = _dbContext.GoodsInfo.OrderByDescending(g=>g.GoodsId).Where(g=>!g.IsDelete&&g.Category == category&&g.State == (int)GoodsState.Shelves).Take(count);
            return goods;
        }
    }
}
